﻿using System;
using Tao.OpenGl;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace Aeon.Framework
{   

/// <summary>
/// File format helper class.
/// Handles all texture format specific features.
///     [TODO] Load TGAs.
///     [BUG] Something is wrong with png's.
/// 
/// </summary>
internal sealed class TextureType
    {
    // --- Attributes:
    
    private Int32 format;       // Image format pixel type.
    private Int32 input;        // Image input pixel format structure.
    private Int32 output;       // Image output pixel format structure.
    
    private UInt16 width;       // Image size, horizontal.
    private UInt16 height;      // Image size, vertical.
    
    // --- Properties:
    
    internal Int32 Format { get { return(format); } }
    internal Int32 Input { get { return(input); } }
    internal Int32 Output { get { return(output); } }
    
    internal UInt16 Width { get { return(width); } }
    internal UInt16 Height { get { return(height); } }
    
    // --- Constructor:
    
    internal TextureType()
        {
        
        }
        
    // --- Public Methods:
     
    /// <summary>
    /// Uploads image data to a byte array.
    /// 
    /// </summary>
    internal byte[] Load(String path)
        {
        Bitmap image = new Bitmap(path);
        height = (ushort)image.Height;
        width = (ushort)image.Width;
        
        int components = findFormats(image);
        int length = height*width*components;
        
        Rectangle area = new Rectangle(0,0,width,height);    
        BitmapData imageData = image.LockBits(area,ImageLockMode.ReadOnly,image.PixelFormat);
        
        byte[] bmp = new byte[length];
        Marshal.Copy(imageData.Scan0,bmp,0,length);            
        image.UnlockBits(imageData);
        
        return(bmp);
        }
        
    // --- Private Methods:
    
    /// <summary>
    /// Discovers and sets pixel input, pixel output, presentation type, makes
    /// any format specific adjustment, and returns the number of pixel components.
    /// 
    /// </summary>    
    private int findFormats(Bitmap img)
        {
        int components = 0;
        System.Drawing.Imaging.ImageFormat x = img.RawFormat;
        
        if (img.PixelFormat == PixelFormat.Format24bppRgb)
            {
            components = 3;
            input = Gl.GL_RGB;
            output = Gl.GL_BGR_EXT;
            format = Gl.GL_UNSIGNED_BYTE;
            }
            
        if (img.PixelFormat == PixelFormat.Format32bppArgb)
            {
            components = 4;
            input = Gl.GL_RGBA;
            output = Gl.GL_BGRA_EXT;
            format = Gl.GL_UNSIGNED_BYTE;
            }
        
        img.RotateFlip(RotateFlipType.RotateNoneFlipY);
                    
        return(components);
        }

    }


}